#!/usr/bin/env python

from Tkinter import *
from random import *
from math import sqrt
import subprocess

def prueba(tamanio_entrada):
	cant=int(random()*tamanio_entrada)
	w=randint(3,int(2*sqrt(tamanio_entrada)))
	h=tamanio_entrada/w
	vs=[]
	for v in range(cant):
		orient=choice(['-','|'])
		if orient=='|':
			l=randint(1,int(h*.5))
			x,y=randint(1,w),randint(1,h-l)
		else:
			l=randint(1,int(w*.5))
			x,y=randint(1,w-l),randint(1,h)
		ok=True
		for v2 in vs:
			if orient=='-':
				if v2[2]=='-' and v2[1]==y and (x<v2[0]<x+l or x<v2[0]+v2[3]<x+l or v2[0]<x<v2[0]+v2[3] or v2[0]<x+l<v2[0]+v2[3] or x==v2[0]): ok=False
			if orient=='|':
				if v2[2]=='|' and v2[0]==x and (y<v2[1]<y+l or y<v2[1]+v2[3]<y+l or v2[1]<y<v2[1]+v2[3] or v2[1]<y+l<v2[1]+v2[3] or y==v2[1]): ok=False
		if ok: vs.append((x,y,orient,l,randint(0,10)))
	offsx,offsy=randint(0,800),randint(0,800)
	return str(randint(0,10))+'\t'+str(len(vs))+'\n'+'\n'.join([str(v[0]+offsx)+' '+str(v[1]+offsy)+' '+v[2]+' '+str(v[3])+' '+str(v[4])+' ' for v in vs])



factor=20
maxx,maxy,w=0,0,0
sp=Spinbox(from_=100,to=1000,increment=1)
canvas = Canvas(width=factor+factor*maxx, height=factor+factor*maxy, bg='lightblue')

def change():
	global canvas
	caso=prueba(int(sp.get()))
	print caso
	print
	vallas=[[int(x[0])]+[int(x[1])]+[x[2]]+[int(x[3])]+[int(x[4])] for x in map(lambda x:x.split(),caso[1:].split('\n')) if len(x)==5]
	maxx=max([x[0]+x[3] for x in vallas if x[2]=='-']+[x[0] for x in vallas if x[2]=='|']+[3])
	maxy=max([x[1]+x[3] for x in vallas if x[2]=='|']+[x[1] for x in vallas if x[2]=='-']+[3])
	w=int(caso.split()[0])
		
	fp=subprocess.Popen(['./floodmapa'], shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
	fp.stdin.write(caso+"\n")
	r=fp.stdout.read().split()
	miny=int(r.pop())
	minx=int(r.pop())
	
	canvas.delete("all")
	canvas.config(width=factor+factor*(maxx-minx), height=factor+factor*(maxy-miny))

	ii,jj=0,0
	for i in r:
		jj=0
		for j in i:
			if j=='0': canvas.create_rectangle(jj*factor, ii*factor, jj*factor+factor, ii*factor+factor, fill="white", width=0)
			jj+=1
		ii+=1
	for v in vallas:
		v[0]-=minx
		v[1]-=miny
		canvas.create_line(v[0]*factor,v[1]*factor,(v[0]+(v[2]=='-' and v[3] or 0))*factor,(v[1]+(v[2]=='|' and v[3] or 0))*factor,fill=(v[4]<w and 'gray70' or 'black'))

change()

Button(text="random",command=change).grid(row=0,column=1)
sp.grid(row=0,column=0)
canvas.grid(row=2,columnspan=2)

mainloop()
